package com.example.demo.controller;

import com.example.demo.bean.ERecord;
import com.example.demo.bean.User;
import com.example.demo.bean.UserInfo;
import com.example.demo.service.ERecordService;
import com.example.demo.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.sql.Date;
import java.time.LocalDate;
import java.util.List;

@Controller
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private ERecordService eRecordService;

    @RequestMapping("/userinfo")
    public String userinfo(Model model) {
        String username = "";
        if(SecurityContextHolder.getContext().getAuthentication().getPrincipal().getClass().toString().equals("class java.lang.String")){
            username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }else {
            UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            username = principal.getUsername();
        }
        System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal().getClass().toString().equals("class java.lang.String"));
        System.out.println(username);
        UserInfo userInfo = userInfoService.getUserInfoByUsername(username);
        model.addAttribute("userInfo", userInfo);
        List<ERecord> eRecords = eRecordService.getERcordByUfid(userInfo.getId());
        if(eRecords.size() == 0){
            eRecordService.addERecord(userInfo.getId());
            ERecord eRecord = eRecordService.getERecordByid(userInfo.getId());
            model.addAttribute("record", eRecord);
        }else{
            ERecord eRecord = eRecords.get(eRecords.size()-1);
            model.addAttribute("record", eRecord);
        }
        return "userInfo";
    }
}
